package com.zlm.app;

import com.zlm.bean.LoginEvent;
import com.zlm.common.BlacklistWarning;
import com.zlm.common.LoginFailWarning;
import org.apache.commons.compress.utils.Lists;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.state.ListState;
import org.apache.flink.api.common.state.ListStateDescriptor;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.TimeCharacteristic;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.timestamps.AscendingTimestampExtractor;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.net.URL;
import java.util.ArrayList;
import java.util.Comparator;

/**
 * Author: Harbour
 * Date: 2021-05-17 15:30
 * Desc: 登录失败监控 APP
 */
public class LoginFailApp {
    public static void main(String[] args) throws Exception {
        // step 1 获取执行环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        env.setStreamTimeCharacteristic(TimeCharacteristic.EventTime);

        // step 2 获取数据源
        URL resource = AdBlacklistApp.class.getResource("/LoginLog.csv");
        DataStream<String> inputDataStream = env.readTextFile(resource.getPath());

        // step 3 转换数据类型
        DataStream<LoginEvent> loginEventDataStream = inputDataStream
                .map(new MapFunction<String, LoginEvent>() {
                    @Override
                    public LoginEvent map(String value) throws Exception {
                        String[] fields = value.split(",");

                        // Long userId, String ip, String loginState, Long timestamp
                        return new LoginEvent(
                            Long.parseLong(fields[0]),
                            fields[1],
                            fields[2],
                            Long.parseLong(fields[3])
                        );
                    }
                })
                .assignTimestampsAndWatermarks(new AscendingTimestampExtractor<LoginEvent>() {
                    @Override
                    public long extractAscendingTimestamp(LoginEvent element) {
                        return element.getTimestamp() * 1000L;
                    }
                });


        // step 4 黑名单处理
        SingleOutputStreamOperator<LoginFailWarning> loginEventWithBlacklistDataStream = loginEventDataStream
                .keyBy(LoginEvent::getUserId)
                .process(new MyBlacklistProcessFunction(2));


        // step 5 开窗统计
//        loginEventWithBlacklistDataStream
//                .keyBy(AdClickEvent::getProvince)
//                .timeWindow(Time.hours(1), Time.minutes(5))
//                .aggregate(new AdBlacklistApp.MyAggFunction(), new AdBlacklistApp.MyFullWindowFunction())
////                .keyBy(AdCountViewByProvince::getWindowEnd)
////                .process(new MyKeyedProcessFunction())
//                .print();

        // step 6 输出黑名单统计信息
        loginEventWithBlacklistDataStream
                .getSideOutput(new OutputTag<BlacklistWarning>("login-fail"){})
                .print("black-list");

        env.execute();
    }

    private static class MyBlacklistProcessFunction extends KeyedProcessFunction<Long, LoginEvent, LoginFailWarning> {

        // 2秒内登录失败的次数，超过则认为是恶意登录
        private final int upperBound;
        // 保存每次登录失败的事件
        private ListState<LoginEvent> loginFailTimeListState;
        // 保存定时器的时间戳
        private ValueState<Long> timerState;

        public MyBlacklistProcessFunction(int upperBound) {
            this.upperBound = upperBound;
        }

        @Override
        public void open(Configuration parameters) throws Exception {
            loginFailTimeListState = getRuntimeContext().getListState(new ListStateDescriptor<LoginEvent>("loginTime-list", LoginEvent.class));
            timerState = getRuntimeContext().getState(new ValueStateDescriptor<Long>("timer-ts", Long.class));
        }

        @Override
        public void processElement(LoginEvent value, Context ctx, Collector<LoginFailWarning> out) throws Exception {

             // 第一种方式 ：判断2秒内登录失败的次数，来判断是否是恶意登录
//            // 如果此次登录事件的状态是失败
//            if ("fail".equalsIgnoreCase(value.getLoginState())) {
//                // 将失败的事件加入状态列表
//                loginFailTimeListState.add(value);
//
//                // 没有定时器，则注册一个定时器
//                if (timerState.value() == null) {
//                    timerState.update(value.getTimestamp() * 1000L + 2000L);
//                    ctx.timerService().registerEventTimeTimer(value.getTimestamp() * 1000L + 2000L);
//                }
//
//            } else {
//                // 如果登录成功了，则需要删除定时器，并清空状态
//                if (timerState.value() != null) {
//                    ctx.timerService().deleteEventTimeTimer(timerState.value());
//                }
//                loginFailTimeListState.clear();
//                timerState.clear();
//            }

            /**
             * 遍历所有登录失败的状态，
             *      如果2秒内连续登录失败，则将其输出侧输出流
             * 如果登录成功，则清空所有的状态
             */

            // 如果此次登录事件的状态是失败
            if ("fail".equalsIgnoreCase(value.getLoginState())) {

                // 获取状态列表，然后根据时间戳排序
                loginFailTimeListState.add(value);
                ArrayList<LoginEvent> loginFailTimeList = Lists.newArrayList(loginFailTimeListState.get().iterator());
                loginFailTimeList.sort(Comparator.comparingLong(LoginEvent::getTimestamp));

                int size = loginFailTimeList.size();

                for (int i = 0; i < size; i++) {

                    Long firstTime = loginFailTimeList.get(i).getTimestamp();
                    Long lastTime = value.getTimestamp();

                    if (firstTime - lastTime <= 2 && size - i + 1 >= upperBound ) {
                        ctx.output(
                                new OutputTag<LoginFailWarning>("login-fail"){},
                                new LoginFailWarning(
                                        value.getUserId(),
                                        firstTime,
                                        lastTime,
                                        "在2秒内登录" + upperBound +"次，过于频繁，已加入黑名单"
                                )
                        );
                        break;
                    }
                }

            } else {
                // 如果登录成功了，则需要清空状态
                loginFailTimeListState.clear();
            }
        }

        @Override
        public void onTimer(long timestamp, OnTimerContext ctx, Collector<LoginFailWarning> out) throws Exception {

            // 获取状态转换为Arraylist，然后根据时间戳排序
            ArrayList<LoginEvent> loginFailTimeList = Lists.newArrayList(loginFailTimeListState.get().iterator());
            loginFailTimeList.sort(Comparator.comparingLong(LoginEvent::getTimestamp));

            // 获取最后一次登录失败的时间与第一次登录失败的时间，用于后面封装LoginFailWarning类
            Long lastTime = loginFailTimeList.get(loginFailTimeList.size() - 1).getTimestamp() * 1000L;
            Long firstTime = loginFailTimeList.get(0).getTimestamp() * 1000L;

            int loginFailCounts = loginFailTimeList.size();

            // 如果2秒内登录失败的次数超过upperBound，则输出侧输出流
            if (loginFailCounts >= upperBound) {
                ctx.output(
                        new OutputTag<LoginFailWarning>("login-fail"){},
                        new LoginFailWarning(
                                ctx.getCurrentKey(),
                                firstTime,
                                lastTime,
                                ctx.getCurrentKey() + "在2秒内登录" + loginFailCounts +"次，过于频繁，已加入黑名单"
                        )
                );
            }

        }
    }
}
